<?php
error_reporting(E_ERROR | E_PARSE);
//test_controlledexposure script created by Robert Cox on April 1st 2011
//Commandline Usage: ./test_controlledexposure.php commandline (debug)
//URL Usage: http://.../../test_controlledexposure.php?web=1              <= normal mode
//      -or- http://.../../test_controlledexposure.php?web=1&debug=1      <= debug mode

// set start time
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;

if(isset($_GET['debug'])){
                $debug = TRUE;
                $GLOBALS["debug"] = TRUE;
        } else {
                unset($debug);
        }

if(isset($_GET['web'])){
                $web = TRUE;
                $GLOBALS["web"] = TRUE;
        } else {
                unset($web);
        }


if (isset($debug)) { 
	echo "<br>* * * * *  D E B U G = O N * * * * *<br>";
	if (isset($web)) { 
		echo "<br>* * * * *  W E B = O N  * * * * *<br>";}
}


$status = "";
$testname = "Controlled Exposure Test";
$testdesc = "Verify Session Based Controlled Exposure is working";
$testurl = "test_controlledexposure.php";
$testtime = time();

// Setup the archival file name for the test
$datestamp = date("YmdGis");
$directory = "/http/matchtest/archived_results/controlledexposuretest/";
#$directory = "/tmp/canary_archived_results/controlledexposuretest/";
if(!is_dir($directory)){
	if(!mkdir($directory, 0777)) {
		die('Failed to create directory: '.$directory);
	}
}


$today = date("F j, Y, g:i a");
$random = rand();
$UserAgent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16";
$Targeting="\"targeting\"";

function TraceInfo($output,$string,$debug) {
        $line_match = array_values(preg_grep("/$string/", $output));
            if (isset($GLOBALS["debug"])) { echo "DEBUG - string:  ".$string."<br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - output:  <br><pre>"; print_r($output); echo "</pre><br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - line_match:<br><pre>"; print_r($line_match); echo "</pre><br>";}
        if(stripos($line_match[0], " = ")){
			$explode = explode(" = ", $line_match[0]); }
        if(stripos($line_match[0], ":")){
			$explode = explode(":", $line_match[0]); }
        if(stripos($line_match[1], ">>>>")){
			$result = $line_match[1]; }
        if (isset($GLOBALS["debug"])) { echo "DEBUG - result:  ".$result."<br>";}
		return $result;
}

// setup command line args (commandline only)

if (isset($argv[1])) { $commandline = $argv[1]; unset($debug);} 

        $AdCallURL = "http://crtldev.aimatch.com:60000";
        $PathInfo = "/canary/hserver/area=contexp/mid=".$testtime."/trace=1";
//        $PathInfo = "/canary/hserver/mid=1964040319620615/trace=1";
        $Query = "";
        $client_headers[] = sprintf('X-Forwarded-For: %s', $ClientIP);

        $url = "$AdCallURL$PathInfo?$Query";

        $delay = 2500;

$i = 1;
while($i <= 10){ // run the test 10 times
        // initilize the curl call
        $ch[$i] = curl_init();
        // set useragent
        curl_setopt($ch[$i], CURLOPT_USERAGENT, $UserAgent);
        // Set curl to use $url for http call
        curl_setopt($ch[$i], CURLOPT_URL, $url);
        // show client headers
        curl_setopt($ch[$i], CURLOPT_HEADER, 1);
        // have curl put X-Forwarded-For into headers
        curl_setopt($ch[$i],CURLOPT_HTTPHEADER, $client_headers);
        // store results as the return of curl_exec
        curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, TRUE);
        // Follow redirects
        curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, TRUE);		
        // if HTML error 400 over over, fail
        curl_setopt($ch[$i], CURLOPT_FAILONERROR, TRUE);

        $output[$i] = curl_exec($ch[$i]);
        if (isset($debug)) { echo "<br><pre><hr>HTTP Response Output:<br><br>"; print_r($output[$i]); echo "</pre><br><hr>"; }
		$testdetail = $testdetail."***** PASS #$i\n".$output[$i]."\n\n";

        $output_array = preg_split('/[\n]/', $output[$i], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
		
        if (isset($debug)) { echo "<br><pre><hr>HTTP Response Output (array):<br><br>"; print_r($output_array); echo "</pre><br><hr>"; }

        //get curl info
        $info[$i] = curl_getinfo($ch[$i]);
        if (isset($debug)) { echo "<br><pre><hr>CURL Response Info:<br><br>"; print_r($info[$i]); echo "</pre><br><hr>"; }

        //close curl connection
        curl_close($ch);

        /** get HTTP return header (code AND text) **/

        $http_response = array_values(preg_grep("/^HTTP/", $output_array));
        $http_array = explode(" ",$http_response[0]);
        $http_return_code = trim($http_array[1]);
        $http_return_text = trim($http_array[2]);
        if (isset($debug)) { echo "<br>DEBUG - HTTP CODE/TEXT: $http_response[0]<br>"; }

        /* check code = 200 and text equal OK, anything else we have an error */
        if ($http_return_text != "OK" || $http_return_code != "200") {
            if (isset($debug)) { echo "***** ALERT - HTTP CODE/TEXT: ".trim($http_response[0])." *****<br>"; }
				echo "HTTP return code/text was not 200/OK". trim($http_response[0])."<br>";
				// *** TODO: Need to put something in here to print a communication error (or response error)
				// out to the 
                die;
        }
   
        $TraceTargeting = TraceInfo($output_array,">>>>");
		$TraceTargetingArray[$i] = $TraceTargeting;
        if(stripos($TraceTargeting, "controlledexposure")){
			$message = "***** PASS #$i - Controlled Exposure Ad: $TraceTargeting";
			if (isset($web)) { echo $message."<br>";}
			if (isset($commandline)) { echo $message."\n\n";}
			$status[$i] = "pass";
			$testsummary = $testsummary.$message."\n";
			$ControlledExpAdCount++;
        }
        else {
			$message = "***** PASS #$i - Non Controlled Exposure Ad: $TraceTargeting";
            if (isset($web)) { echo $message."<br>";}
            if (isset($commandline)) { echo $message."\n\n";}
			$status[$i] = "fail";
			$testsummary = $testsummary.$message."\n";
			$NonControlledExpAdCount++;
		}
$i++;
}        
// Determine if the test was successful
if (isset($web)) { echo "<br><pre><hr>Total Results:<br><br>"; print_r($TraceTargeting); echo "</pre><br><hr>"; }

if(($ControlledExpAdCount == 3)&&($NonControlledExpAdCount == 7)){
	if (isset($web)) { echo "***** SUCCESS - Session Based Controlled Exposure Targeting IS WORKING<br>";}
	// Build the Success text to put in the archived file.
	$message1 = "***** SUCCESS - Session Based Controlled Exposure Targeting IS WORKING\n";
	$status = "pass";
}
else {
    if (isset($web)) { echo "***** ALERT - Session Based Controlled Exposure Targeting IS NOT WORKING<br>";}
    if (isset($web)) { echo "***** Controlled Exposure Ads = $ControlledExpAdCount<br>";}
    if (isset($web)) { echo "***** Non Controlled Exposure Ads = $NonControlledExpAdCount<br>";}
	// Build the failure text to put in the archived file.
	$message1 = "***** ALERT - Session Based Controlled Exposure Targeting IS NOT WORKING\n";
	$message1 = $message1."***** Controlled Exposure Ads = $ControlledExpAdCount\n";
	$message1 = $message1."***** Non Controlled Exposure Ads = $NonControlledExpAdCount\n";
	$status = "fail";
}



// Write out the information to the testresults.txt file.

$lines = file('/http/matchtest/testresults.txt');
$numitems = count($lines);

// Loop through our array, show HTML source as HTML source; and line numbers too.
if (isset($debug)) { echo "<br><pre><hr>HTTP Response Output:<br><br>"; print_r($lines); echo "</pre><br><hr>"; }

$newfile = $lines[0];
$i=1;
while($i <= $numitems) {
	$pieces = explode("|",$lines[$i]);
	if($testname == $pieces[1]){
		$replaced_line = $status."|".$testname."|".$testdesc."|".$testurl."|".$testtime."\n";
		$newfile = $newfile.$replaced_line;
	}
	else{
		$newfile = $newfile.$lines[$i];
	}
	$i++;
}

if (isset($debug)) { echo "<br><pre><hr>New File Output:<br><br>"; print_r($newfile); echo "</pre><br><hr>"; }

$fp = fopen('/http/matchtest/testresults.txt', 'w');
fwrite($fp, $newfile);
fclose($fp);

if (isset($web)) { echo "<br><pre><hr>Test Detail:<br><br>".$testdetail."</pre><br><hr>"; }
if (isset($commandline)) { echo "\n\n---------------------\nTest Detail:\n\n".$testdetail."\n\n"; }

echo "<pre>Test Detail: ".$testdetail."</pre>";

// Write out results of the test to a file 
if (isset($web)) { $testfilename = $directory."controlledexposuretest.web.".$status.".".$datestamp.".".$testtime.".txt"; }
if (isset($commandline)) { $testfilename = $directory."controlledexposuretest.commandline.".$status.".".$datestamp.".".$testtime.".txt"; }

if (!$fp1 = fopen($testfilename,'w')) {
    echo "Cannot open file ($testfilename)";
    exit;
}

fwrite ($fp1,$testsummary."\n\n");
fwrite ($fp1,"\n\n---------------------\nTest Detail:\n\n".$testdetail."\n\n");
fclose($fp1);


if (isset($debug)) { phpinfo(); }
?>
